#include <opencv2/opencv.hpp>
#include <dlib/opencv.h>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing.h>
#include <nadjieb/mjpeg_streamer.hpp>
#include <chrono>
#include <iomanip>
#include "FaceRecognizer.h"
#include "PerformanceTimer.h"
#include <fstream>
#include <map>
#include <csignal>  // 添加信号处理头文件
#include <atomic>   // 添加原子操作头文件

using namespace std;
using namespace dlib;

// 配置参数
#define DETECTION_INTERVAL 10  // 每隔多少帧检测一次人脸
#define PORT 8080              // 视频流端口

// 原子变量用于信号处理
std::atomic<bool> running(true);

// 信号处理函数
void signalHandler(int signum) {
    if (signum == SIGINT) {
        running = false;
    }
}

// 从配置文件加载配置
std::map<std::string, std::string> loadConfig(const std::string& configPath) {
    std::map<std::string, std::string> config;
    std::ifstream file(configPath);
    if (!file) {
        cerr << "无法打开配置文件: " << configPath << endl;
        return config;
    }

    std::string line;
    while (std::getline(file, line)) {
        size_t pos = line.find('=');
        if (pos != std::string::npos) {
            std::string key = line.substr(0, pos);
            std::string value = line.substr(pos + 1);
            config[key] = value;
        }
    }
    return config;
}

// 将cv_image<bgr_pixel>转换为matrix<rgb_pixel>
dlib::matrix<dlib::rgb_pixel> convert_to_rgb_matrix(const dlib::cv_image<dlib::bgr_pixel>& img) {
    dlib::matrix<dlib::rgb_pixel> rgb_img;
    dlib::assign_image(rgb_img, dlib::mat(img));
    return rgb_img;
}

// 获取本地IP地址的简化版本
std::string getLocalIP() {
    // 简单替代方案 - 使用 hostname 命令
    FILE* pipe = popen("hostname -I | awk '{print $1}'", "r");
    if (!pipe) return "无法获取IP";
    
    char buffer[128];
    std::string result = "";
    if (fgets(buffer, sizeof(buffer), pipe)) {
        result = buffer;
        // 移除换行符
        if (!result.empty() && result[result.size()-1] == '\n') {
            result.erase(result.size()-1);
        }
    }
    pclose(pipe);
    return result.empty() ? "无法获取IP" : result;
}

int main() {
    // 注册信号处理函数
    signal(SIGINT, signalHandler);
    
    // 获取本地IP地址
    std::string localIP = getLocalIP();
    
    // 加载配置文件
    const std::string configPath = "/home/hhy212306170/practice/dlib/s4/config.txt";
    std::map<std::string, std::string> config = loadConfig(configPath);
    if (config.empty()) {
        cerr << "配置文件加载失败或为空" << endl;
        return -1;
    }

    // 初始化人脸识别器
    FaceRecognizer faceRecognizer(config);
    if (!faceRecognizer.initialize()) {
        cerr << "人脸识别器初始化失败" << endl;
        return -1;
    }
    faceRecognizer.printFaceLibInfo();  // 打印人脸库信息

    // 打印访问信息
    cout << "=============================================" << endl;
    cout << "视频流服务已启动，请打开浏览器访问以下地址：" << endl;
    cout << "本地访问: http://localhost:" << PORT << "/bgr" << endl;
    cout << "外部访问: http://" << localIP << ":" << PORT << "/bgr" << endl;
    cout << "=============================================" << endl;
    cout << "按 Ctrl+C 退出程序" << endl;

    // 初始化视频捕获
    cv::VideoCapture cap(0);
    if (!cap.isOpened()) {
        cerr << "无法打开摄像头" << endl;
        return -1;
    }

    // 设置摄像头分辨率
    cap.set(cv::CAP_PROP_FRAME_WIDTH, 640);
    cap.set(cv::CAP_PROP_FRAME_HEIGHT, 480);

    // 初始化MJPEG流服务器
    nadjieb::MJPEGStreamer streamer;
    streamer.start(PORT);
    
    // JPEG编码参数
    std::vector<int> params = {cv::IMWRITE_JPEG_QUALITY, 90};

    int frame_count = 0;
    cv::Mat frame;
    std::vector<std::pair<rectangle, std::string>> faceResults;  // 存储人脸识别结果

    // 性能计时器
    TimerManager& timerMgr = TimerManager::getInstance();
    auto frameTimer = timerMgr.getOrCreateTimer("帧捕获和处理全过程");
    auto detectTimer = timerMgr.getOrCreateTimer("人脸检测");
    auto alignTimer = timerMgr.getOrCreateTimer("人脸校正");
    auto recognizeTimer = timerMgr.getOrCreateTimer("人脸匹配");
    auto streamTimer = timerMgr.getOrCreateTimer("推流");

    // 主循环
    while (running) {
        // 开始帧计时
        frameTimer->start();
        
        // 捕获帧
        cap >> frame;
        if (frame.empty()) {
            cerr << "获取帧失败" << endl;
            break;
        }

        // 每隔DETECTION_INTERVAL帧检测一次人脸
        if (frame_count % DETECTION_INTERVAL == 0) {
            faceResults.clear();  // 清除上一帧的结果
            
            // 转换为dlib格式 (cv_image<bgr_pixel>)
            cv_image<bgr_pixel> dlib_img(frame);
            
            // 转换为matrix<rgb_pixel>类型
            dlib::matrix<dlib::rgb_pixel> rgb_img = convert_to_rgb_matrix(dlib_img);
            
            // 人脸检测计时
            detectTimer->start();
            std::vector<rectangle> faces = faceRecognizer.detectFaces(rgb_img);
            detectTimer->end();
            
            // 处理每个检测到的人脸
            for (const auto& face : faces) {
                try {
                    // 人脸对齐计时
                    alignTimer->start();
                    dlib::matrix<rgb_pixel> face_chip = faceRecognizer.alignFace(rgb_img, face);
                    alignTimer->end();
                    
                    // 人脸识别计时
                    recognizeTimer->start();
                    std::string identity = faceRecognizer.recognizeFace(face_chip);
                    recognizeTimer->end();
                    
                    // 保存结果用于后续绘制
                    faceResults.emplace_back(face, identity);
                    
                } catch (const std::exception& e) {
                    cerr << "人脸处理错误: " << e.what() << endl;
                }
            }
        }

        // 绘制人脸框和识别结果
        for (const auto& [face, identity] : faceResults) {
            // 绘制人脸矩形
            cv::rectangle(frame, 
                cv::Point(face.left(), face.top()),
                cv::Point(face.right(), face.bottom()),
                cv::Scalar(0, 255, 0), 2);
            
            // 绘制识别结果
            cv::putText(frame, identity, 
                        cv::Point(face.left(), face.top() - 10),
                        cv::FONT_HERSHEY_SIMPLEX, 0.7,
                        cv::Scalar(0, 255, 0), 2);
        }

        // 推流计时
        streamTimer->start();
        std::vector<uchar> buff_bgr;
        cv::imencode(".jpg", frame, buff_bgr, params);
        streamer.publish("/bgr", std::string(buff_bgr.begin(), buff_bgr.end()));
        streamTimer->end();
        
        // 结束帧计时
        frameTimer->end();

        frame_count++;

        // 短暂等待以减少CPU占用
        cv::waitKey(1);
    }

    // 释放资源
    streamer.stop();
    cap.release();
    
    // 打印性能报告
    cout << "\n=============================================" << endl;
    cout << "性能统计报告：" << endl;
    cout << "=============================================" << endl;
    timerMgr.printAllSummaries();
    cout << "=============================================" << endl;
    
    cout << "程序已退出" << endl;
    return 0;
}